package com.love;

public class TreeTotal {


    static class TreeNode{

        public int val;

        public TreeNode left;

        public TreeNode right;


        public TreeNode(int val,TreeNode left,TreeNode right){
            this.val = val;
            this.left = left;
            this.right = right;
        }
    }


    public static TreeNode getTree(int[] pre,int[] in){
        if(pre == null || pre.length == 0 || in == null || in.length == 0 || pre.length != in.length){
            return null;
        }

        TreeNode head = process(pre, 0, pre.length - 1, in, 0, in.length - 1);
        return head;

    }

    public static TreeNode process(int[] pre,int l1,int r1,int[] in,int l2,int r2){
        if(l1 > r1){
            return null;
        }
        if(l2 > r2){
            return null;
        }
        TreeNode head = new TreeNode(pre[l1],null,null);
        int headVal = pre[l1];
        int find = 0;
        for (int i = 0; i < in.length; i++) {
            if(in[i] == headVal){
                find = i;
                break;
            }
        }
        head.left = process(pre,l1 + 1,l1 + (find - l2),in,l2,find-1);
        head.right = process(pre,l1 + (find - l2) + 1,r1,in,find + 1,r2);
        return head;

    }





    public static int nums(TreeNode head){
        if(head == null){
            return 0;
        }
        int left = nums(head.left);
        int right = nums(head.right);
        return left + right + 1;
    }

//    public static void total(TreeNode head,int[] scores){
//        if(head == null){
//            return;
//        }
//        total(head.left,scores);
//        total(head.right,scores);
//    }

    public static int total(TreeNode head){
        if(head == null){
            return 0;
        }
        int left = total(head.left);

        int right = total(head.right);
        System.out.println(left + right + head.val);

        return left + right + head.val;
    }




    public static void main(String[] args) {
//        int[] pre = {3,9,20,15,7};
//        int[] in = {9,3,15,20,7};
        int[] pre = {6,7,-2,9,6};
        int[] in = {7,-2,6,6,9};


        TreeNode tree = getTree(pre, in);
//        System.out.println(nums(tree));
        System.out.print(total(tree) + " ");
    }





}
